import zipimport, re, datetime
django = zipimport.zipimporter('django_dev.zip').load_module('django')
from django.http import HttpResponse, HttpResponseRedirect
#from django.core.files import File
from calportal.mainpage.models import *
from django.shortcuts import render_to_response, redirect
from google.appengine.api import users
from django.utils import simplejson as json
from calportal.mainpage.upload import UploadForm
from google.appengine.ext import db
from calportal.mainpage.add_new import NewItemForm, NewCommentForm
from calportal.mainpage.form_edit_profile import ProfileForm
from django.core import serializers

def index(request):
  error = ''
  if request.method == 'POST':
    data = NewItemForm(data=request.POST)
    due = request.POST['due'].split('/')
    if data.is_valid and due:
      entity = data.save(commit=False)
      #entity.resource = NULL
      #entity.due = request.POST['due'] 
      entity.created_by = users.get_current_user()
      entity.due = datetime.date(int(due[2]), int(due[0]), int(due[1]))
      entity.put()
      return redirect('/')
    else:
      return 'Error'
  user = users.get_current_user()
  if not user:
    return redirect(users.create_login_url('/'))
  user_info = UserInfo.gql('WHERE user = :user_id', user_id=user).get()
  if not user_info:
    return redirect('/editprofile.html')
  sections = [Section.get(section_key) for section_key in user_info.classes]
  """
  items = Item.gql('WHERE section IN :section AND due >= :now AND '
                   'due != NULL ORDER BY due ASC LIMIT 10',
                   now=datetime.datetime.now(), section=user_info.classes)
  """
  items = Item.gql('WHERE section IN :section LIMIT 10',
                   section=user_info.classes).fetch(10)
  if items:
    items = sorted(items, key=lambda x: x.due)
  #d = now('mm/dd/yy')
  item_clumps = []
  for item in items:
    comments = []
    for comment in item.getComments():
      ta = ThumbAction.gql('WHERE comment=:comment AND user=:user', comment=comment, user=user).get()
      if ta and ta.action == 'UP':
        comments.append((comment,1))
      elif ta and ta.action == 'DOWN':
        comments.append((comment,-1))
      else:
        comments.append((comment, 0))
    item_clumps.append((item, comments))
  payload = dict(items=item_clumps, add_new=NewItemForm(), user=user.nickname(),
                 logout_link=users.create_logout_url('/'), sections=sections)
  return render_to_response('index.html', payload)
  
def api(request):
  """An api to access things such as major lists, etc.  Returns a json list"""
  if request.method == 'GET':
    callback = request.GET['callback']
    type = request.GET['type']
    #query = request.GET['query']
    if type == 'majors':
      majors = []
      for item in Major.all():
        #m = re.search(query, item.short_name)
        #if m:
        majors.append(item.short_name)
      """
      for item in MajorNames.all():
        majors.append(name)
      """
      data = 'majorslist ="'+" ".join(majors) + '";'
      return HttpResponse(data, mimetype="text/javascript")

def settings(request):
  """This page modifies a user's profile, including adding and removing classes
  the user is signed up for."""
  user = users.get_current_user()
  payload = {}
  if not user:
    return redirect(users.create_login_url('/'))
  user_info = UserInfo.gql('WHERE user = :user_id', user_id=user).get()
  if not user_info:
    payload['form'] = UserSettingsForm()
  else:
    payload['form'] = UserSettingsForm(instance=user_info)
  payload['sections'] = [Section.get(section_key) for section_key in userinfo.classes]
  return render_to_response('settings.html', payload)
  
##########################################################
# Below is code for adding classes into the appengine db #
##########################################################
  
def upload(request):
  if request.method == 'POST':
    # TODO: Add admin authentication
    form = UploadForm(request.POST, request.FILES)
    if form.is_valid():
      uploaded_file = request.FILES['upload_file']
      filename = uploaded_file.name
      obj = json.loads(uploaded_file.read())
      messages = 'Messages: \n' + str(obj)
      if filename == 'majors.json':
        for major_short, major_long in obj:
          major = Major(key_name=major_short, short_name=major_short, long_name=major_long)
          major.put()
      elif filename == 'classes.json':
        for majorshort, class_short, class_long, url in obj:
          major = Major.get_by_key_name(majorshort)
          _class = Classes(major=major, short_name=class_short, 
              key_name='%s %s' % (majorshort, class_short), long_name=class_long)
          _class.put()
      elif filename == 'sections.json':
        for (m_short, c_short, s_type, s_num, s_parent, s_time, s_loc, instr, ccn,
            last_updated, books_url, pri) in obj:
          _class = Classes.get_by_key_name('%s %s'%(m_short, c_short))
          major = _class.major
          try:
            if ccn:
              ccn = int(ccn.split(' ')[0])
            else:
              ccn = None
          except Exception:
            ccn = None
          # "COMPSCI 61A - LEC 001"
          if pri:
            pri = "TRUE"
          else:
            continue
          section = Section(key_name='%s - %s %s' % (_class.key().name(), s_type, s_num), 
          classes=_class, type=s_type, num=s_num, time=s_time, location=s_loc,
          instructor=instr, ccn=str(ccn), last_updated=last_updated, books_url=books_url,
          primary=pri)
          if not pri:
            pass
            """
            pri_type, pri_num = s_parent
            section.primary_lec = Section.get_by_key_name(
                '%s - %s %s' % (_class.key().name(), pri_type, pri_num))
            """
          section.put()
      return render_to_response('upload.html', dict(message=messages))
  else:
    form = UploadForm()
  return render_to_response('upload.html', {'form': form})
  
def delete(request, name):
  q = db.GqlQuery('SELECT * FROM %s' % name)
  message = 'Number of entries: %d' % q.count()
  db.delete(q.fetch(200))
  return render_to_response('upload.html', {'message': message})
  
def classes(request, major=None, _class=None):

  user = users.get_current_user()
  if not user:
    return redirect(users.create_login_url('/'))
  user_info = UserInfo.gql('WHERE user = :user_id', user_id=user).get()
  if not user_info:
    return redirect('/editprofile.html')
  m = None
  c = None
  if major:
    m = Major.get_by_key_name(major)
  if _class:
    c = Classes.get_by_key_name('%s %s' % (major, _class))
  major_list = []
  class_list = []
  section_list = []
  class_data = {}
  subtitle = ''
  if not m:
    title = 'Pick your classes'
    for major_entry in Major.all().fetch(200):
      major_list.append((major_entry.short_name, major_entry.long_name.title()))
  elif not c:
    title = m.long_name
    for class_entry in Classes.gql('WHERE major = :1 ORDER BY __key__ ASC', m).fetch(200):
      class_list.append((m.short_name, class_entry.short_name, class_entry.long_name))
  else:
    title = c.long_name
    subtitle = '%s %s' % (m.short_name, c.short_name)
    for section in Section.gql('WHERE classes = :1', c).fetch(200):
      section_list.append({'type':section.type, 'num':section.num, 'ccn':section.ccn,
          'teacher':section.instructor, 'time':section.time, 'loc':section.location,
          'key':section.key(), 'primary':section.primary == 'TRUE'})
  return render_to_response('classes.html',
      {'major_list': major_list, 'class_list': class_list, 'title': title,
          'section_list':section_list, 'm':m, 'user':user.nickname(), 'sections':[Section.get(section_key) for section_key in user_info.classes]})
      
def input_major(request):
  user = users.get_current_user()
  if request.method == "POST":
    major_name = request.POST['major']
    major = Major.get_by_key_name(major_name)
    if major:
      return redirect('/classes/%s' % major_name)
  return redirect('/classes')  

def add_class(request):
  user = users.get_current_user()
  if request.method == "POST":
    section_key = request.POST['section_key']
    user_info = UserInfo.gql('WHERE user=:user_id', user_id=user).get()
    section = Section.get(section_key)
    if section.key() not in user_info.classes:
      user_info.classes.append(section.key())
      user_info.put()
  return redirect('/classes')
  
def remove_class(request):
  user = users.get_current_user()
  if request.method == "GET":
    section_key = request.GET['section_key']
    user_info = UserInfo.gql('WHERE user=:user_id', user_id=user).get()
    section = Section.get(section_key)
    if section.key() in user_info.classes:
      user_info.classes.remove(section.key())
      user_info.put()
  return redirect('/editprofile.html')
    
  
def remove_item(request, item_key):
  user = users.get_current_user()
  item = Item.get(item_key)
  if item and item.created_by == user:
    Item.delete(item)
  return redirect('/')
  
def remove_comment(request, comment_key):
  user = users.get_current_user()
  comment = Comment.get(comment_key)
  if comment and comment.created_by == user:
    Comment.delete(comment)
  return redirect('/')
    
def add_comment(request):
  user = users.get_current_user()
  if request.method == "POST":
    content = request.POST['content']
    item_key = request.POST['item_key']
    item = Item.get(item_key)
    Comment(content=content, item=item, created_by=user).put()
  return redirect('/')
          
def edit_profile(request):
  error = ''
  user = users.get_current_user()
  if not user:
    return redirect(users.create_login_url('/'))
  userinfo = UserInfo.gql('WHERE user = :user_id', user_id=user).get()
  if request.method == 'POST':
    if userinfo == None:
      userinfo = ProfileForm(request.POST)
      userinfo.save(commit=False)
    else:
      userinfo = ProfileForm(request.POST, instance=userinfo)
    userinfo.save();
    userinfo = UserInfo.gql('WHERE user = :user_id', user_id=user).get()
  if userinfo == None:
    defaults = dict()
  else:
    defaults = dict(first_name=userinfo.first_name,
                    last_name=userinfo.last_name,
                    profile=userinfo.profile,
                    user=userinfo.user,
                    berkeley_email=userinfo.berkeley_email,
                    grad=userinfo.grad)
    if userinfo.major:
      defaults['major'] = userinfo.major.key()
  profileform = ProfileForm(initial=defaults)
  payload = dict(profileform=profileform, user=user.nickname(), logout_link=users.create_logout_url('/'))
  if userinfo:
    payload['sections'] = [Section.get(section_key) for section_key in userinfo.classes]
  return render_to_response('editprofile.html', payload)
  
def thumbs_up(request, comment_key):
  user = users.get_current_user()
  comment = Comment.get(comment_key)
  ta = ThumbAction.gql('WHERE comment=:comment AND user=:user', comment=comment, user=user).get()
  if ta:
    if ta.action == 'DOWN':
      comment.thumbs_down_count -= 1
      comment.thumbs_up_count += 1
      ta.action = 'UP'
      ta.put()
    elif ta.action == 'UP': # Thumbs up again, remove it.
      comment.thumbs_up_count -= 1
      comment.put()
      ta.action = None
      ta.put()
    else:
      comment.thumbs_up_count += 1
      comment.put()
      ta.action = 'UP'
      ta.put()
  else:
    comment.thumbs_up_count += 1
    ThumbAction(comment=comment, user=user, action='UP').put()
  comment.put()
  return redirect('/')

def thumbs_down(request, comment_key):
  user = users.get_current_user()
  comment = Comment.get(comment_key)
  ta = ThumbAction.gql('WHERE comment=:comment AND user=:user', comment=comment, user=user).get()
  if ta:
    if ta.action == 'UP':
      comment.thumbs_up_count -= 1
      comment.thumbs_down_count += 1
      comment.put()
      ta.action = 'DOWN'
      ta.put()
    elif ta.action == 'DOWN': # Thumbs down again, remove it.
      comment.thumbs_down_count -= 1
      comment.put()
      ta.action = None
      ta.put()
    else: # Must have removed an action earlier.
      comment.thumbs_down_count += 1
      comment.put()
      ta.action = 'DOWN'
      ta.put()
  else:
    comment.thumbs_down_count += 1
    comment.put()
    ThumbAction(comment=comment, user=user, action='DOWN').put()
  return redirect('/')
  
  
def update_resource(request):
  user = users.get_current_user()
  item_key = request.POST['item_id']
  item = Item.get(item_key)
  item.resource = request.POST['resource']
  item.last_editor = user
  item.put()
  return redirect('/')